package cn.kgc.task;

import cn.kgc.entity.MessageInfo;
import cn.kgc.service.MessageInfoService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 定时任务
 *
 * @author YC
 */
@Component
@EnableScheduling
public class TimerTask_xxljob {

    @Value("${mq.maxResend}")
    private int maxResend;

    @Resource
    private MessageInfoService messageInfoService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 定时查询数据库中应发送待发送的消息列表，根据条件执行逻辑
     */
    @XxlJob("updateOrSendTask")
    public ReturnT<Void> updateOrSendTask(String param) {
        // 查询待发送的消息列表
        List<MessageInfo> messageInfos = messageInfoService.listReadyMessage();
        messageInfos.forEach(messageInfo -> {
            if (messageInfo.getSequence() >= maxResend) {
                // 超过最大发送次数的信息标记死亡
                messageInfoService.messageMaxDead(messageInfo.getId());
            } else {
                // 没有超过最大发送次数的信息 将发送次数+1后重新发送
                messageInfoService.messageResend(messageInfo.getId());
                MessageProperties messageProperties = new MessageProperties();
                messageProperties.setHeader("sequence", messageInfo.getSequence() + 1);
                messageProperties.setDelay(messageInfo.getDelayTime().intValue());
                messageProperties.setHeader("delayTime", messageInfo.getDelayTime());
                Message rabbitMessage =
                        new Message(messageInfo.getPayload().getBytes(StandardCharsets.UTF_8), messageProperties);
                rabbitTemplate.convertAndSend(messageInfo.getExchange(), messageInfo.getRoutingKey(),
                        rabbitMessage, new CorrelationData(messageInfo.getId()));
            }
        });
        return new ReturnT<>();
    }

}
